import 'package:cave_flutter/network/whl_api.dart';
import 'package:cave_flutter/pages/whl_mine/setting/shipping_address/shipping_address_list_logic.dart';
import 'package:cave_flutter/utils/whl_toast_utils.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

class EditShippingAddressLogic extends GetxController {
  ShippingAddressItemModel? item;
  int isDefault = 0;
  TextEditingController nameController = TextEditingController();
  TextEditingController phoneController = TextEditingController();
  TextEditingController addressController = TextEditingController();

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
    var arguments = Get.arguments;
    if (arguments != null) {
      item = arguments['item'];
      nameController.text = item?.name ?? '';
      phoneController.text = item?.phone ?? '';
      addressController.text = item?.receiveAddress ?? '';
      isDefault = item?.isDefault ?? 0;
    }
  }

  void setDefault() {
    isDefault = isDefault == 1 ? 0 : 1;
    update();
  }

  void onConfirm() async {
    if (nameController.text.isEmpty) {
      MyToast.show('请输入收件人姓名');
      return;
    }

    if (phoneController.text.isEmpty) {
      MyToast.show('请输入收件人手机号');
      return;
    }

    if (addressController.text.isEmpty) {
      MyToast.show('请输入收件地址');
      return;
    }

    var params = {
      'isDefault': isDefault,
      'name': nameController.text,
      'phone': phoneController.text,
      'receiveAddress': addressController.text,
    };

    if (item != null) {
      params['id'] = item?.id ?? '';
    }

    ResponseData responseData = await WhlApi.saveUserReceiveAddress.post(params, withLoading: true);
    if (responseData.isSuccess()) {
      if (item != null) {
        MyToast.show("编辑成功");
      } else {
        MyToast.show("添加成功");
      }
      ShippingAddressListLogic logic = Get.find<ShippingAddressListLogic>();
      logic.requestData();
      Get.back();
    } else {
      MyToast.show(responseData.msg ?? "操作失败");
    }
  }

  void loadData() {}
  void saveDate() {}
}
